package cn.richx.pushmessage.web.rest.message;

import cn.richx.pushmessage.domain.UserDTO;
import cn.richx.pushmessage.message.PushItem;
import cn.richx.pushmessage.rpc.feign.UserService;
import cn.richx.pushmessage.service.PushMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author caohao
 * @date 2018-04-23
 */
@RestController
@RequestMapping("/api/message")
public class PushMessageRest {

    private final static Logger logger = LoggerFactory.getLogger(PushMessageRest.class);

    private final PushMessageService service;
    private final UserService userService;

    public PushMessageRest(PushMessageService service, UserService userService) {
        this.service = service;
        this.userService = userService;
    }

    @ModelAttribute
    public UserDTO getLoginUser(@RequestHeader("X-BaseID") String baseId) {
        String phone = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserDTO user = userService.getUserByPhone(phone, baseId).getResponseObject();
        return user;
    }

    /**
     * 单条推送
     * */
    @PostMapping("/push")
    public Map<String, Object> push(@RequestBody PushItem pushItem) {
        Map<String, Object> resp = new HashMap<String, Object>();
        logger.info(pushItem.getPushSender());
        try {
            service.push(pushItem, resp);
            resp.put("ResponseResult", "推送成功");
            resp.put("ResponseCode", 0);
        } catch (Exception e) {
            resp.put("ResponseResult", "推送失败");
            resp.put("ResponseCode", -1);
            e.printStackTrace();
        }
        return resp;
    }

    /**
     * 异步单条推送
     * */
    @PostMapping("/push/async")
    public Map<String, Object> asyncPush(@RequestBody PushItem pushItem) {
        Map<String, Object> resp = new HashMap<String, Object>();
        try {
            service.asyncPush(pushItem);
            resp.put("ResponseResult", "推送成功");
            resp.put("ResponseCode", 0);
        } catch (Exception e) {
            resp.put("ResponseResult", "推送失败");
            resp.put("ResponseCode", -1);
            e.printStackTrace();
        }
        return resp;
    }

    /**
     * 批量推送
     * */
    @PostMapping("/push/batch")
    public Map<String, Object> push(@RequestBody List<PushItem> pushItemList) {
        Map<String, Object> resp = new HashMap<String, Object>();
        try {
            service.push(pushItemList);
            resp.put("ResponseResult", "推送成功");
            resp.put("ResponseCode", 0);
        } catch (Exception e) {
            resp.put("ResponseResult", "推送失败");
            resp.put("ResponseCode", -1);
            e.printStackTrace();
        }
        return resp;
    }

    /**
     * 异步批量推送
     * */
    @PostMapping("/push/async/batch")
    public Map<String, Object> asyncPush(@RequestBody List<PushItem> pushItemList) {
        Map<String, Object> resp = new HashMap<String, Object>();
        try {
            service.asyncPush(pushItemList);
            resp.put("ResponseResult", "推送成功");
            resp.put("ResponseCode", 0);
        } catch (Exception e) {
            resp.put("ResponseResult", "推送失败");
            resp.put("ResponseCode", -1);
            e.printStackTrace();
        }
        return resp;
    }

    /**
     * 只给 userId 进行异步推送
     * */
    @PostMapping("/push/async/batch/onlyId")
    public Map<String, Object> asyncPushOnlyId(@RequestBody List<PushItem> pushItemList, @RequestHeader("X-BaseID") String baseId) {
        Map<String, Object> resp = new HashMap<String, Object>();
        try {
            service.asyncPushOnlyId(pushItemList, baseId);
            resp.put("ResponseResult", "推送成功");
            resp.put("ResponseCode", 0);
        } catch (Exception e) {
            resp.put("ResponseResult", "推送失败");
            resp.put("ResponseCode", -1);
            e.printStackTrace();
        }
        return resp;
    }

    /**
     * 获取未读取消息
     * */
    @GetMapping("/last/{lastId}")
    public Map<String, Object> getNoReadMessageList(@ModelAttribute UserDTO user, @PathVariable Long lastId) {
        Map<String, Object> resp = new HashMap<String, Object>();
        try {
            resp.put("ResponseResult", "数据获取成功");
            resp.put("ResponseObject", service.getNoReadList(user, lastId));
            resp.put("ResponseCode", 0);
        } catch (Exception e) {
            resp.put("ResponseResult", "数据获取失败");
            resp.put("ResponseCode", -1);
            e.printStackTrace();
        }
        return resp;
    }

    /*public static void main(String[] args) {
        *//*String apiKey = "fyWBYCBRMLGBThpbXiSXQadD";
        String secretKey = "2G2uXWBtKu4X2PQrQ5Najw1IwPX1DGGS";*//*
        String apiKey = "249No3utppAyO89q2tC3a20L";
        String secretKey = "Gf2ng4EFOMUyAESr0fHsUg5OZYcyCFcB";
        PushKeyPair pair = new PushKeyPair(apiKey,secretKey);
        BaiduPushClient pushClient = new BaiduPushClient(pair,
            BaiduPushConstants.CHANNEL_REST_URL);
        pushClient.setChannelLogHandler((YunLogEvent event) -> {
            System.out.println(event.getMessage());
        });

        PushMsgToSingleDeviceRequest request = new PushMsgToSingleDeviceRequest()
            .addDeviceType(4)
            .addChannelId("5524492428656120675")
            .addMsgExpires(3600)
            .addMessageType(1)
            .addMessage("{\"title\":\"测试推送\",\"description\":\"收到了吗? 收到QQ跟我说一下\"}");
        try {
            PushMsgToSingleDeviceResponse response = pushClient.
                pushMsgToSingleDevice(request);
        } catch (PushClientException e) {
            e.printStackTrace();
        } catch (PushServerException e) {
            e.printStackTrace();
        }

    }*/

    /*public static void main(String[] args) throws PushServerException, PushClientException {

        // 1. get apiKey and secretKey from developer console
        String apiKey = "249No3utppAyO89q2tC3a20L";
        String secretKey = "Gf2ng4EFOMUyAESr0fHsUg5OZYcyCFcB";
        PushKeyPair pair = new PushKeyPair(apiKey, secretKey);

        // 2. build a BaidupushClient object to access released interfaces
        BaiduPushClient pushClient = new BaiduPushClient(pair,
            BaiduPushConstants.CHANNEL_REST_URL);

        // 3. register a YunLogHandler to get detail interacting information
        // in this request.
        pushClient.setChannelLogHandler(new YunLogHandler() {
            @Override
            public void onHandle(YunLogEvent event) {
                System.out.println(event.getMessage());
            }
        });

        try {
            // 4. specify request arguments
            // make IOS Notification
            JSONObject notification = new JSONObject();
            JSONObject jsonAPS = new JSONObject();
            jsonAPS.put("alert", "Hello Baidu Push");
            jsonAPS.put("sound", "ttt"); // 设置通知铃声样式，例如"ttt"，用户自定义。
            notification.put("aps", jsonAPS);
            notification.put("key1", "value1");
            notification.put("key2", "value2");

            PushMsgToSingleDeviceRequest request = new PushMsgToSingleDeviceRequest()
                .addChannelId("5524492428656120675")
                .addMsgExpires(new Integer(3600)). // 设置message的有效时间
                addMessageType(1).// 1：通知,0:透传消息.默认为0 注：IOS只有通知.
                addMessage(notification.toString()).addDeployStatus(1). // IOS,
                // DeployStatus
                // => 1: Developer
                // 2: Production.
                    addDeviceType(4);// deviceType => 3:android, 4:ios
            // 5. http request
            PushMsgToSingleDeviceResponse response = pushClient
                .pushMsgToSingleDevice(request);
            // Http请求结果解析打印
            System.out.println("msgId: " + response.getMsgId() + ",sendTime: "
                + response.getSendTime());
        } catch (PushClientException e) {
            *//*
             * ERROROPTTYPE 用于设置异常的处理方式 -- 抛出异常和捕获异常,'true' 表示抛出, 'false' 表示捕获。
             *//*
            if (BaiduPushConstants.ERROROPTTYPE) {
                throw e;
            } else {
                e.printStackTrace();
            }
        } catch (PushServerException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                throw e;
            } else {
                System.out.println(String.format(
                    "requestId: %d, errorCode: %d, errorMessage: %s",
                    e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
            }
        }

    }*/
}
